package com.waypolice.common.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import com.waypolice.common.utils.ReadProperties;

import sun.misc.BASE64Encoder;

/**
 * 数米科技短息发送接口(单个发送)
 * @author wr
 *
 */
public class SmsSend {
	
	/**
	 * 	短信调用方法
	 * @param phone(存放电话号码)
	 * @param count(存放发送内容)
	 * @return	提交成功，返回当前提交数据的唯一标记ID,为null发送不成功
	 */
	public static String sendMSG(String phone,String count) {
		Properties properties = ReadProperties.getProperties("caseFailureTime.properties");
		String SMS_UserName = properties.getProperty("SMS_UserName");
		String SMS_PassWord = properties.getProperty("SMS_PassWord");
		
		// 接口地址
		String ulr = "http://api.shumi365.com:8090/sms/send.do";
		// 客户ID，必填
		String userid = SMS_UserName;
		// 时间戳，必填
		String timespan = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());// 当前时间转化为yyyymmddhhmmss;
		// 原始密码，必填
		String password = SMS_PassWord;
		// MD5加密后密码
		String pwd = getMD5(password + timespan);//原始密码+时间戳做MD5加密，32位大写格式
		// 手机号，必填
		String mobile = phone;
		// 内容，必填
		String content = count;
		// 扩展，选填，可为空，请先询问是否有扩展权限
		String ext = "";
		// 定时时间，选填，可为空
		String attime = "";
		// 选填，如果不填默认为GBK，可以选填GBK或者UTF8/UTF-8
		//String msgfmt = "gbk";
		String msgfmt = "gbk";
		//接收短信回执结果
		String result=null;
		
		StringBuilder sendData = new StringBuilder();
		
		BASE64Encoder encoder = new BASE64Encoder();
		try {
			String content_base64 = encoder.encode(content.getBytes(msgfmt));// 做base64加密操作,编码方式使用msgfmt
			sendData.append("userid=").append(userid)
					.append("&pwd=").append(pwd)
					.append("&timespan=").append(timespan)
					.append("&mobile=").append(mobile)
					.append("&content=").append(content_base64)
					.append("&ext=").append(ext)
					.append("&attime=").append(attime);
			
			// 发送短信
			result = httpPost(ulr, sendData.toString(), msgfmt);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;		
	}
	
	/**
	 * http协议提交
	 * @param ulr
	 * @param data
	 * @param charset
	 * @return
	 */
	public static String httpPost(String ulr, String data,String charset) {
		
		URL url=null;
		try {
			url=new URL(ulr);
			HttpURLConnection conn=(HttpURLConnection)url.openConnection();
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);
			conn.setConnectTimeout(30*1000);
			conn.setReadTimeout(30*1000);
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			
			OutputStream out=conn.getOutputStream();
			out.write(data.getBytes(charset));
			out.close();
			
			BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream(),charset));
			StringBuilder response = new StringBuilder();
			String result;
			while (null!=(result=in.readLine())) {
				response.append(result).append("\n");
			}
			in.close();
			return response.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 方法名称：getMD5 
	 * 功    能：字符串MD5加密 
	 * 参    数：待转换字符串 
	 * 返 回 值：加密之后字符串
	 */
	public static String getMD5(String sourceStr){
		String resultStr = "";
		try {
			byte[] temp = sourceStr.getBytes();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(temp);
			// resultStr = new String(md5.digest());
			byte[] b = md5.digest();
			for (int i = 0; i < b.length; i++) {
				char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
						'9', 'A', 'B', 'C', 'D', 'E', 'F' };
				char[] ob = new char[2];
				ob[0] = digit[(b[i] >>> 4) & 0X0F];
				ob[1] = digit[b[i] & 0X0F];
				resultStr += new String(ob);
			}
			return resultStr;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
}
